package pathfind;

import data.NavmeshRegion;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dmitry
 */
public class PathSmoother {

    private NavmeshRegion polygon;
    private List<Point> path;

    public PathSmoother(NavmeshRegion polygon, List<Point> path) {
        this.polygon = polygon;
        this.path = path;
    }

    public List<Point> smooth() {
        List<Point> newPath = new ArrayList<>();
        int start = 0;
        int nextPoint = 2;
        newPath.add(path.get(start));
        boolean cycle = true;
        while (cycle) {
            for (int i = nextPoint; i < path.size(); i++) {
                if (isWalkable(start, nextPoint)) {
                    nextPoint += 1;
                } else {
                    newPath.add(path.get(nextPoint));
                    start = nextPoint;
                    nextPoint += 3;
                }
                if (nextPoint >= path.size()) {
                    newPath.add(path.get(path.size() - 1));
                    return newPath;
                }
            }
            if (nextPoint >= path.size()) {
                newPath.add(path.get(path.size() - 1));
                return newPath;
            }
        }
        return newPath;
    }

    private boolean isWalkable(int index1, int index2) {
        Point a = path.get(index1);
        Point b = path.get(index2);
        return polygon.checkVisionLine(a.x, a.y, b.x, b.y);
    }
}